package com.xm.servlet.background.orders;

import com.google.gson.Gson;
import com.xm.entity.Commodity;
import com.xm.entity.CommodityInsurance;
import com.xm.entity.CommoditySpecification;
import com.xm.entity.Orders;
import com.xm.exception.SqlErrorException;
import com.xm.service.background.CommodityInsuranceService;
import com.xm.service.background.CommodityService;
import com.xm.service.background.CommoditySpecificationService;
import com.xm.service.background.OrdersService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 康文程
 * @date 2024-1-9 下午 05:55
 */
@WebServlet("/background/orders")
public class OrdersServlet extends HttpServlet {
    /**
     * 订单Service
     */
    private final OrdersService service = new OrdersService();
    /**
     * 商品Service
     */
    private final CommodityService commodityService = new CommodityService();
    /**
     * 商品规格
     */
    private final CommoditySpecificationService commoditySpecificationService =
            new CommoditySpecificationService();
    /**
     * 商品保险
     */
    private final CommodityInsuranceService commodityInsuranceService =
            new CommodityInsuranceService();

    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String orderId = req.getParameter("orderId");
        Orders orderByOrderId = service.getOrderByOrderId(orderId);
        String separate = ",";
        String multipleSeparate = "[|]";
        String isNotNull = "null";
        List<Commodity> commoditiesByIds = new ArrayList<>();
        if (orderByOrderId.getCommodityIds().contains(separate)) {
            multipleProductOrders(orderByOrderId,orderByOrderId.getWarehouseId(),commoditiesByIds, separate,isNotNull,multipleSeparate);
        } else {
            ordersForIndividualItems(orderByOrderId,orderByOrderId.getWarehouseId(),commoditiesByIds,separate,isNotNull);
        }
        orderByOrderId.setCommodityList(commoditiesByIds);
        resp.getWriter().println(new Gson().toJson(orderByOrderId));
    }

    /**
     * 多个商品 查询规格和保险
     * @param orderByOrderId 订单编号
     * @param separate 分隔多个规格、多个保险
     * @param isNotNull 是否为空
     * @param multipleSeparate 分隔多个商品
     * @throws SqlErrorException 抛出错误
     */
    public void multipleProductOrders(Orders orderByOrderId,Integer warehouseId ,List<Commodity> commoditiesByIds, String separate,String isNotNull,String multipleSeparate) throws SqlErrorException {
        String[] commodityIds = orderByOrderId.getCommodityIds().split(separate);
        List<Commodity> commoditieList = commodityService.getCommoditiesByIds(commodityIds,warehouseId);
        //多个商品
        for (int i = 0; i < commoditieList.size(); i++) {
            // 获取商品关联的所有规格信息
            List<CommoditySpecification> commoditySpecifications = commoditySpecificationService.
                    getCommoditySpecificationsByCommodityId(commoditieList.get(i).getCommodityId());
            List<CommodityInsurance> commodityInsuranceByCommodityId =
                    commodityInsuranceService.
                            getCommodityInsuranceByCommodityId(commoditieList.get(i).getCommodityId());
            //多个商品规格
            for (String specificationId : orderByOrderId.getSpecificationIds().split(multipleSeparate)[i].split(separate)) {
                //多个规格
                for (CommoditySpecification commoditySpecification : commoditySpecifications) {
                    if (commoditySpecification.getSpecificationId() == Integer.parseInt(specificationId)) {
                        /// 获取需要修改的 Commodity 对象
                        Commodity commodity = commoditieList.get(i);
                        // 获取 CommoditySpecification 列表，如果为 null 则新建一个列表
                        List<CommoditySpecification> commoditySpecificationList =
                                commodity.getCommoditySpecification();
                        if (commoditySpecificationList == null) {
                            commoditySpecificationList = new ArrayList<>();
                        }
                        // 将新元素添加到列表中
                        commoditySpecificationList.add(commoditySpecification);
                        // 将更新后的列表设置回 Commodity 对象中的 CommoditySpecification 属性
                        commodity.setCommoditySpecification(commoditySpecificationList);

                    }
                }
            }
            if (orderByOrderId.getInsuranceIds().contains("|")) {
                //多个商品有多个保险或一个
                for (String specificationId : orderByOrderId.getInsuranceIds().split(multipleSeparate)[i].split(separate)) {
                    for (CommodityInsurance commodityInsurance : commodityInsuranceByCommodityId) {
                        if (!specificationId.equals(isNotNull)) {
                            if (commodityInsurance.getInsuranceId() == Integer.parseInt(specificationId)) {
                                /// 获取需要修改的 Commodity 对象
                                Commodity commodity = commoditieList.get(i);
                                // 获取 CommoditySpecification 列表，如果为 null 则新建一个列表
                                List<CommodityInsurance> commoditySpecificationList =
                                        commodity.getCommodityInsurances();
                                if (commoditySpecificationList == null) {
                                    commoditySpecificationList = new ArrayList<>();
                                }
                                // 将新元素添加到列表中
                                commoditySpecificationList.add(commodityInsurance);
                                // 将更新后的列表设置回 Commodity 对象中的 CommoditySpecification 属性
                                commodity.setCommodityInsurances(commoditySpecificationList);
                            }
                        }
                    }
                }
            } else if (orderByOrderId.getInsuranceIds().contains(separate)) {
                for (String specificationId : orderByOrderId.getInsuranceIds().split(separate)) {
                    for (CommodityInsurance commodityInsurance : commodityInsuranceByCommodityId) {
                        if (!specificationId.equals(isNotNull)) {
                            if (commodityInsurance.getInsuranceId() == Integer.parseInt(specificationId)) {
                                /// 获取需要修改的 Commodity 对象
                                Commodity commodity = commoditieList.get(i);
                                // 获取 CommoditySpecification 列表，如果为 null 则新建一个列表
                                List<CommodityInsurance> commoditySpecificationList =
                                        commodity.getCommodityInsurances();
                                if (commoditySpecificationList == null) {
                                    commoditySpecificationList = new ArrayList<>();
                                }
                                // 将新元素添加到列表中
                                commoditySpecificationList.add(commodityInsurance);
                                // 将更新后的列表设置回 Commodity 对象中的 CommoditySpecification 属性
                                commodity.setCommodityInsurances(commoditySpecificationList);
                            }
                        }
                    }
                }
            }
        }
        commoditiesByIds.addAll(commoditieList);
    }
    /**
     * 单个商品 查询规格和保险
     * @param orderByOrderId 订单
     * @param warehouseId 仓库ID
     * @param commoditiesByIds 商品
     * @param separate 分隔
     * @param isNotNull 是否为空
     */
    public void ordersForIndividualItems(Orders orderByOrderId,Integer warehouseId,List<Commodity> commoditiesByIds, String separate,String isNotNull){
        Commodity commodityById = commodityService.getCommodityByIdAndByWarehouseId(Integer.parseInt(orderByOrderId.getCommodityIds()),warehouseId);
        List<CommoditySpecification> commoditySpecifications = commoditySpecificationService.
                getCommoditySpecificationsByCommodityId(commodityById.getCommodityId());
        List<CommodityInsurance> commodityInsuranceByCommodityId =
                commodityInsuranceService.
                        getCommodityInsuranceByCommodityId(commodityById.getCommodityId());

        //多个商品规格
        for (String specificationId : orderByOrderId.getSpecificationIds().split(separate)) {
            //多个规格
            for (CommoditySpecification commoditySpecification : commoditySpecifications) {
                if (commoditySpecification.getSpecificationId() == Integer.parseInt(specificationId)) {
                    // 获取 CommoditySpecification 列表，如果为 null 则新建一个列表
                    List<CommoditySpecification> commoditySpecificationList =
                            commodityById.getCommoditySpecification();
                    if (commoditySpecificationList == null) {
                        commoditySpecificationList = new ArrayList<>();
                    }
                    // 将新元素添加到列表中
                    commoditySpecificationList.add(commoditySpecification);
                    // 将更新后的列表设置回 Commodity 对象中的 CommoditySpecification 属性
                    commodityById.setCommoditySpecification(commoditySpecificationList);
                }
            }
        }
        // 处理单个商品的情况， 保险是否为空
        if (!orderByOrderId.getInsuranceIds().equals(isNotNull)){
            //处理多个保险
            for (String specificationId : orderByOrderId.getInsuranceIds().split(separate)) {
                for (CommodityInsurance commodityInsurance : commodityInsuranceByCommodityId) {
                    if (!specificationId.equals(isNotNull)){
                        if (commodityInsurance.getInsuranceId() == Integer.parseInt(specificationId.isEmpty() ? "0" : specificationId)){
                            // 获取 CommoditySpecification 列表，如果为 null 则新建一个列表
                            List<CommodityInsurance> commoditySpecificationList =
                                    commodityById.getCommodityInsurances();
                            if (commoditySpecificationList == null) {
                                commoditySpecificationList = new ArrayList<>();
                            }
                            // 将新元素添加到列表中
                            commoditySpecificationList.add(commodityInsurance);
                            // 将更新后的列表设置回 Commodity 对象中的 CommoditySpecification 属性
                            commodityById.setCommodityInsurances(commoditySpecificationList);
                        }
                    }
                }
            }
        }
        commoditiesByIds.add(commodityById);
    }
}
